const express = require('express');
const https = require('https');
const fs = require('fs');
const { Server } = require('socket.io');

// 创建 Express 应用
const app = express();

// 读取 SSL 证书文件
const sslOptions = {
    key: readSslFile('localhost.key'),
    cert: readSslFile('localhost.crt')
};

// 读取 SSL 文件的辅助函数，添加错误处理
function readSslFile(filePath) {
    try {
        return fs.readFileSync(filePath);
    } catch (error) {
        console.error(`Failed to read SSL file ${filePath}:`, error);
        process.exit(1);
    }
}

// 静态文件服务
app.use(express.static(__dirname + '/public'));

// 设置 Content-Security-Policy 中间件
app.use((req, res, next) => {
    res.setHeader('Content-Security-Policy', "default-src 'self'; media-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src *");
    next();
});

// 创建 HTTPS 服务器
const server = https.createServer(sslOptions, app);

// 创建 Socket.IO 服务器
const io = new Server(server);

// 处理 Socket.IO 连接
io.on('connection', (socket) => {
    console.log('一个用户连接');

    // 处理加入房间事件
    socket.on('join-room', (roomId) => {
        socket.join(roomId);
        console.log(`用户加入房间: ${roomId}`);
    });

    // 处理 offer 事件
    socket.on('offer', (roomId, offer) => {
        validateAndBroadcast(socket, roomId, 'offer', offer);
    });

    // 处理 answer 事件
    socket.on('answer', (roomId, answer) => {
        validateAndBroadcast(socket, roomId, 'answer', answer);
    });

    // 处理 ice-candidate 事件
    socket.on('ice-candidate', (roomId, candidate) => {
        validateAndBroadcast(socket, roomId, 'ice-candidate', candidate);
    });

    // 处理断开连接事件
    socket.on('disconnect', () => {
        console.log('一个用户断开');
    });
});

// 验证并广播消息的辅助函数
function validateAndBroadcast(socket, roomId, eventName, data) {
    if (typeof data === 'object' && data !== null) {
        socket.to(roomId).emit(eventName, data);
    } else {
        console.warn(`Invalid data received for event ${eventName}:`, data);
    }
}

// 获取端口号
const port = process.env.PORT || 3000;

// 启动服务器
server.listen(port, () => {
    console.log(`Server running on port https://localhost:${port} `);
});

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
    // 可以根据实际情况选择是否退出进程
    process.exit(1);
});

// 处理未处理的 Promise 拒绝
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});